import { uDb, cline } from 'sui';
import { g_db } from 'db/state';

const calc_pos = (num) => {
    const tray = g_db.boxtray();

    const n = parseInt(num / tray, 10);
    const p = num % tray;

    if (p === 0) {
        if (tray < 10) {
            return `${n}-0${tray}`;
        }

        return `${n}-${tray}`;
    }

    if (p < 10) {
        return `${n + 1}-0${p}`;
    }

    return `${n + 1}-${p}`;
};

const insert_box = (box_sn, psn, pos, hok, herr) => {
    const val = { sn: psn };
    if (pos) {
        val["pos"] = pos;
    }

    uDb(null, `file/md/box_${box_sn}`,
        {
            line: cline(),
            sn: psn,
            v: val,
        },
        r => hok(), e => herr("保存数据失败，请重新扫码"));
};

export {calc_pos, insert_box};
